package com.example.chapter06.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.chapter06.entity.CartInfo;
import com.example.chapter06.entity.GoodsInfo;

import java.util.ArrayList;
import java.util.List;

public class ShoppingDBHelper extends SQLiteOpenHelper {
    //数据库名称
    private static final String DB_NAME = "shopping.db";

    private static final String TABLE_GOODS_INFO = "goods_info";

    private static final String TABLE_CART_INFO = "cart_info";
    private static final int DB_VERSION = 1;

    private SQLiteDatabase mWDB = null;
    private SQLiteDatabase mRDB = null;

    private static ShoppingDBHelper mHelper = null;

    private ShoppingDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    public static ShoppingDBHelper getInstance(Context context) {
        if (mHelper == null) {
            mHelper = new ShoppingDBHelper(context);
        }
        return mHelper;
    }

    public SQLiteDatabase openReadLink() {
        if (mRDB == null || !mRDB.isOpen()) {
            mRDB = mHelper.getReadableDatabase();
        }
        return mRDB;
    }

    public SQLiteDatabase openWriteLink() {
        if (mWDB == null || !mWDB.isOpen()) {
            mWDB = mHelper.getWritableDatabase();
        }
        return mWDB;
    }

    public void closeLink() {
        if (mWDB != null && mWDB.isOpen()) {
            mWDB.close();
        }

        if (mRDB != null && mRDB.isOpen()) {
            mRDB.close();
        }
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建商品信息表
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_GOODS_INFO + " (_id INTEGER PRIMARY KEY " +
                "AUTOINCREMENT NOT NULL,name VARCHAR NOT NULL,description VARCHAR NOT NULL,price FLOAT NOT NULL" +
                ", pic_path VARCHAR NOT NULL);";

        db.execSQL(sql);

        //创建购物车信息表
        sql = "CREATE TABLE IF NOT EXISTS " + TABLE_CART_INFO + " (_id INTEGER PRIMARY KEY " +
                "AUTOINCREMENT NOT NULL,goods_id INTEGER NOT NULL,count INTEGER NOT NULL" +
                ");";

        /*_id是为了可移植*/

        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    //添加多条商品信息
    public void insertGoodsInfo(List<GoodsInfo> list) {
        //插入多条记录，要么全部成功，要么全部失败
        try {
            mWDB.beginTransaction();
            for (GoodsInfo info : list) {
                ContentValues values = new ContentValues();
                values.put("name", info.getName());
                values.put("description", info.getDescription());
                values.put("price", info.getPrice());
                values.put("pic_path", info.getPicPath());
                mWDB.insert(TABLE_GOODS_INFO, null, values);
            }
            mWDB.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e("liu", "插入失败");
        } finally {
            mWDB.endTransaction();
        }
    }

    public List<GoodsInfo> queryAllGoodsInfo() {
        String sql = "select * from " + TABLE_GOODS_INFO;
        List<GoodsInfo> list = new ArrayList<>();
        Cursor cursor = mRDB.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            GoodsInfo info = new GoodsInfo();
            info.setId(cursor.getInt(0));
            info.setName(cursor.getString(1));
            info.setDescription(cursor.getString(2));
            info.setPrice(cursor.getFloat(3));
            info.setPicPath(cursor.getString(4));
            list.add(info);
        }
        cursor.close();
        return list;
    }

    //添加商品到购物车
    public void insertCartInfo(int goodsId) {
        //如果购物车中不存在该商品，添加一条信息
        CartInfo cartInfo = queryCartInfoByGoodsId(goodsId);
        ContentValues values = new ContentValues();
        values.put("goods_id", goodsId);
        if (cartInfo == null) {
            values.put("count", 1);
            mWDB.insert(TABLE_CART_INFO, null, values);
        } else {
            //如果购物车已经存在该商品，更新商品数量
            int count = cartInfo.getCount();
            values.put("count", ++count);
            mWDB.update(TABLE_CART_INFO, values, "_id=?",
                    new String[]{String.valueOf(cartInfo.getId())});
        }

    }

    //根据商品id查询购物车信息
    private CartInfo queryCartInfoByGoodsId(int goodsId) {
        Cursor cursor = mRDB.query(TABLE_CART_INFO, null, "goods_id=?",
                new String[]{String.valueOf(goodsId)}, null, null, null);
        CartInfo info = null;
        if (cursor.moveToNext()) {
            info = new CartInfo();
            info.setId(cursor.getInt(0));
            info.setGoods_id(cursor.getInt(1));
            info.setCount(cursor.getInt(2));

        }
        cursor.close();
        return info;
    }

    //统计购物车中商品的总数量
    public int countCartInfo() {
        int count = 0;
        String sql = "select sum(count) from " + TABLE_CART_INFO;
        Cursor cursor = mRDB.rawQuery(sql, null);
        if (cursor.moveToNext()) {
            count = cursor.getInt(0);
        }
        cursor.close();
        return count;
    }

    public List<CartInfo> queryAllCartInfo() {
        List<CartInfo> list = new ArrayList<>();
        Cursor cursor = mRDB.query(TABLE_CART_INFO, null, null, null, null,
                null, null);
        while (cursor.moveToNext()) {
            CartInfo info = new CartInfo();
            info.setId(cursor.getInt(0));
            info.setGoods_id(cursor.getInt(1));
            info.setCount(cursor.getInt(2));
            list.add(info);
        }
        cursor.close();
        return list;
    }

    //根据商品ID查询商品信息
    public GoodsInfo queryGoodsInfoById(int goodsId) {
        GoodsInfo goodsInfo = null;
        Cursor cursor = mRDB.query(TABLE_GOODS_INFO, null, "_id=?", new String[]{String.valueOf(goodsId)},
                null, null, null);
        if (cursor.moveToNext()) {
            goodsInfo = new GoodsInfo();
            goodsInfo.setId(cursor.getInt(0));
            goodsInfo.setName(cursor.getString(1));
            goodsInfo.setDescription(cursor.getString(2));
            goodsInfo.setPrice(cursor.getFloat(3));
            goodsInfo.setPicPath(cursor.getString(4));
        }
        cursor.close();
        return goodsInfo;
    }

    //根据商品id删除购物车信息
    public void deleteCartInfoByGoodsId(int goodsId) {
        mWDB.delete(TABLE_CART_INFO,"goods_id=?",new String[]{String.valueOf(goodsId)});

    }

    public void deleteAllCartInfo(){
        mWDB.delete(TABLE_CART_INFO,"1=1",null);
    }
}
